package mobile.android.Hotel;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import android.sax.Element;
import android.sax.EndElementListener;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.util.Xml;

public class BaseFeedParser {

	static String feedUrlString = "http://softech-ios.googlecode.com/svn/hotel/vn/hotel_danang.xml";
	
	// names of the XML tags

	
	private final URL feedUrl;

	protected BaseFeedParser(){
		try {
			this.feedUrl = new URL(feedUrlString);
		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		}
	}

	protected InputStream getInputStream() {
		try {
			return feedUrl.openConnection().getInputStream();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	public ArrayList<Hotel> parse() {
		final Hotel currentHotel = new Hotel();
		RootElement root = new RootElement("rss");
		final ArrayList<Hotel> hotel = new ArrayList<Hotel>();
		//Element itemlist = root.getChild("");
		Element item = root.getChild("entry");
		item.setEndElementListener(new EndElementListener(){
			public void end() {
				hotel.add(currentHotel.copy());
			}
		});
		item.getChild("name").setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				currentHotel.setName(body);
			}
		});
		item.getChild("address").setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				currentHotel.setAdd(body);
			}
		});
		item.getChild("phone").setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				currentHotel.setPhone(body);
			}
		});
		item.getChild("web").setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				currentHotel.setWeb(body);
			}
		});
		item.getChild("logo").setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				currentHotel.setLogo(body);
			}
		});
		item.getChild("price").setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				currentHotel.setPrince(body);
			}
		});
		item.getChild("level").setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				currentHotel.setLv(Integer.parseInt(body));
			}
		});
		try {
			Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return hotel;
	}
}